<template>
	<div class="index" style="background: rgb(246, 250, 255);" >
    <van-nav-bar title="海报分享" left-arrow  @click-left="onClickLeft" />
    <div style=" padding:0.3rem;">
      <div style="background: #fff; border-radius:0.3rem; overflow: hidden;">
        <div><img :src="$route.query.share_img" style="width: 100%; border-radius:0.3rem;"></div>
        <div class="flex">
          <div style="width: 4.6rem; padding: 0.3rem;">
            <div style="font-size: 0.28rem;">{{$route.query.title}}</div>
            <div class="flexc" style="padding: 0.2rem 0;">
              <div><img :src="$route.query.logo" style="width: 0.4rem; height: 0.4rem; border-radius: 0.2rem;"></div>
              <div style="margin-left: 0.15rem; font-size: 0.24rem; color: rgb(64, 66, 71);">{{$route.query.shopname}}</div>
            </div>
            <div style="color: rgb(175, 179, 188); font-size: 0.2rem;">长按识别二维码进入下单链接</div>
          </div>
          <div style="width: 2rem; padding: 0.3rem 0;"><img :src="img2" style="width: 2rem; height: 2rem; "></div>
        </div>
      </div>
      <div class="flex" style="justify-content: space-around; margin-top: 0.4rem;">
        <div style="width: 3.3rem; height: 0.8rem; font-size: 14px; background: rgb(64, 156, 255);  cursor: pointer; color: rgb(255, 255, 255); border-radius: 0.4rem;" class="flexcc" v-if="!weixin" @click="fenxianglogs()">保存照片</div>
        <div style="width: 3.3rem; height: 0.8rem; font-size: 14px; background: rgb(64, 156, 255);  cursor: pointer; color: rgb(255, 255, 255); border-radius: 0.4rem;" class="flexcc" @click="fenxianglogs(2)" v-if="weixin">保存照片</div>
        <div style="width: 3.3rem; height: 0.8rem; font-size: 14px; background: rgb(228, 237, 255); color: rgb(0, 90, 255); cursor: pointer; border-radius: 0.4rem;" class="flexcc" @click="fuzhi">复制链接</div>
      </div>
    </div>
    <van-popup v-model="fenxiangtulog2" style="width: 7.5rem; background: #fff !important;">
    	<img :src="img3" style="width: 100%;">
    </van-popup>
	</div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  import * as qiniu from 'qiniu-js'

  var h = document.documentElement.clientWidth / 7.5 + 'px';
  document.documentElement.style.fontSize = h;

	export default {
		name: 'query',
		data() {
			return {
        fenxiangtulog2:false,
        img3:"",
        img2:"",
        weixin:false
			}
		},
		created() {
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/micromessenger/i) == 'micromessenger') {
           this.weixin = true
      }
		},
		mounted() {
      document.title = "海报分享"
      console.log(this.$route.query.erweima)
      let url2 = this.$route.query.erweima
      var d = document.createElement('div')
      d.setAttribute('id','erweimadiv')
      document.body.appendChild(d)
      var qrcode = new QRCode(document.getElementById('erweimadiv'), {
          text: url2,
          width: 220,
          height: 220,
          colorDark : "#000000",
          colorLight : "#ffffff",
          correctLevel : QRCode.CorrectLevel.H
      })
      var canvas = document.getElementById("erweimadiv").getElementsByTagName("canvas")[0];
      this.img2 = canvas.toDataURL("image/png");

      document.body.removeChild(d)
		},
		methods: {
      fuzhi:function(){
        this.copy(this.$route.query.erweima)
      },
      onClickLeft:function(){
        this.$router.back(-1)
      },
      fenxianglogs:function(item){
        
        vant.Toast('进入后长按图片保存');
        setTimeout(()=>{
          this.haibao(item)
        },1000)
        // this.xuanzhongde = item
        

      },
      haibao:function(weixin){


      	var that = this
      	var canvas = document.createElement('canvas')
      	canvas.width = 750
      	canvas.height = 300
      	var ctx = canvas.getContext('2d');
      	var canvas_h = 0
      	var img = new Image();
      	let p = new Promise((res,rej)=>{
      		if(this.$route.query.share_img){
      			img.src = this.$route.query.share_img
      			img.setAttribute("crossOrigin",'Anonymous')
      			img.onload = function() {
      				let img_w = 750
      				let bili = 750 / img.width
      				let img_h = parseInt(img.height * bili)
              console.log(img_h)
      				canvas_h = img_h
      				canvas.setAttribute("height", canvas_h + 260);
      				ctx.drawImage(img,0,0,img_w,img_h);  // 将图像绘制到Canvas上
      				res('ok')
      			};
      			img.onerror = function(err){
      				// that.msg = JSON.stringify(err)
      			}
      		}else{
            vant.Toast('没有分享图不能分享');
            return
      			// res('ok')
      		}
      	})
      	p.then(()=>{

      		var img2 = new Image();
      		img2.src = this.img2
      		img2.setAttribute("crossOrigin",'Anonymous')
      		img2.onload = function() {

            ctx.fillStyle = '#000';
            ctx.font = "bold 28px microsoft yahei";
            ctx.maxWidth = '400px'
            ctx.textBaseline = "top";

            let hang1 = that.$route.query.title.substring(0,18) || ''
            let hang2 = that.$route.query.title.substring(18,36) || ''
            ctx.fillText(hang1, 30,canvas_h+35)
            ctx.fillText(hang2, 30,canvas_h+70)

            // ctx.fillText(that.$route.query.title,30,canvas_h+30)

            ctx.drawImage(img2,520,canvas_h+30,200,200);


            ctx.fillStyle = '#000';
            ctx.font = "bold 24px microsoft yahei";
            ctx.lineHight = "40px";
            ctx.maxWidth = '300px'
            ctx.lineHeight = '40px'
            ctx.textBaseline = "top";
            ctx.fillText(that.$route.query.shopname,85,canvas_h+120)


            ctx.fillStyle = 'rgb(175, 179, 188)';
            ctx.font = "20px microsoft yahei";
            ctx.textBaseline = "top";
            ctx.fillText('长按识别二维码 进入下单链接',30,canvas_h+190)


            var img22 = new Image();
            img22.src = that.$route.query.logo
            img22.setAttribute("crossOrigin",'Anonymous')

            img22.onload = function() {
              ctx.drawImage(img22,30,canvas_h+110,40,40);
              var radius = 50;
              // 开始绘制圆角矩形路径
              ctx.beginPath();
              // 左上角
              ctx.arc(radius, radius, radius, Math.PI, Math.PI * 1.5);
              // 右上角
              ctx.arc(canvas.width - radius, radius, radius, Math.PI * 1.5, Math.PI * 2);
              // 右下角
              ctx.arc(canvas.width - radius, canvas.height - radius, radius, 0, Math.PI * 0.5);
              // 左下角
              ctx.arc(radius, canvas.height - radius, radius, Math.PI * 0.5, Math.PI);
              // 结束绘制路径
              ctx.closePath();
              // 将路径限制到绘图区域内
              ctx.clip();
              ctx.drawImage(img22,30,canvas_h+110,40,40);

              var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
              for(var i = 0; i < imageData.data.length; i += 4) {
              	if(imageData.data[i + 3] == 0) {
              		imageData.data[i] = 255;
              		imageData.data[i + 1] = 255;
              		imageData.data[i + 2] = 255;
              		imageData.data[i + 3] = 255;
              	}
              }
              ctx.putImageData(imageData, 0, 0);
              var url = canvas.toDataURL('image/png');


              //下载相关
              // var addElement = document.createElement('a')
              // addElement.href = url
              // addElement.download = "海报.png"
              // document.body.appendChild(addElement)
              // addElement.click();
              // document.body.removeChild(addElement);

              const blob = that.base64ImgtoFile(url)

              that.uploadok(blob,weixin)

            }
      		}
      	})
      },
      base64ImgtoFile(dataurl, filename = 'file') {
              //将base64格式分割：['data:image/png;base64','XXXX']
              const arr = dataurl.split(',')
              // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
              // image/png
              const mime = arr[0].match(/:(.*?);/)[1]  //image/png
              //[image,png] 获取图片类型后缀
              const suffix = mime.split('/')[1] //png
              const bstr = atob(arr[1])   //atob() 方法用于解码使用 base-64 编码的字符串
              let n = bstr.length
              const u8arr = new Uint8Array(n)
              while (n--) {
                  u8arr[n] = bstr.charCodeAt(n)
              }
              return new File([u8arr], `${filename}.${suffix}`, {
                  type: mime
              })
      },
      getRandomChar:function(len = 11)  {
        var  x = "0123456789qwertyuioplkjhgfdsazxcvbnm" // 需要什么字符这里添加
        var  tmp = ""
        var timestamp = new Date().getTime();
        for(var  i=0;i<len;i++)  {
          tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
        }
        return  timestamp+tmp;
      },
      uploadok: function(file,weixin) {
        let name = this.getRandomChar() + '.' + file.name.split('.')[1]
        var that = this
        axios.post(`/api/qiniu/uploadtoken`,{name:name})
          .then(response => {
            if(response.data.msg.code == 0){
              const observer = {
                next(res){
                  console.log(res)
                },
                error(err){
                  console.log(err)
                },
                complete(res){
                  if(weixin == 2){
                    location.href = 'https://gperson.gantanhaokeji.top/'+ res.key
                  }else{
                    var addElement = document.createElement('a')
                    addElement.href = 'https://gperson.gantanhaokeji.top/'+ res.key + '?attname='
                    addElement.download = "海报.png"
                    document.body.appendChild(addElement)
                    addElement.click();
                    document.body.removeChild(addElement);
                  }

                }
              }
              const observable = qiniu.upload(file,name, response.data.data.token, {}, {})
              const subscription = observable.subscribe(observer) // 上传开始
            }else{
              this.$message.error(response.data.msg.info);
            }
          });
      },
		}
	}
</script>


<style scoped lang="less">
  .index{

  }
</style>
